import { useState, useEffect, useRef, useCallback } from "react";
import {
  Layout,
  Button,
  Typography,
  Space,
  Spin,
  Card,
  Tooltip,
  Input,
  Dropdown,
  message,
  Menu,
  Tabs,
} from "antd";
import PlayCircleOutlined from "@ant-design/icons/PlayCircleOutlined";
import BookOutlined from "@ant-design/icons/BookOutlined";
import SyncOutlined from "@ant-design/icons/SyncOutlined";
import DownloadOutlined from "@ant-design/icons/DownloadOutlined";
import QuestionCircleOutlined from "@ant-design/icons/QuestionCircleOutlined";
import GithubOutlined from "@ant-design/icons/GithubOutlined";
import FileTextOutlined from "@ant-design/icons/FileTextOutlined";
import EditOutlined from "@ant-design/icons/EditOutlined";
import { GraphiQL } from "graphiql";
import { explorerPlugin } from "@graphiql/plugin-explorer";
import { createGraphiQLFetcher } from "@graphiql/toolkit";
import MonacoEditor from "react-monaco-editor";
import "./graphiql.css";
import "./plugin-explorer.css";
import "./GraphQLExplorer.css";
import EditorJson from "./EditorJson.jsx";

const { Header, Content, Footer } = Layout;
const { Text, Link } = Typography;
// const { TabPane } = Tabs;

const GraphQLExplorer = () => {
  // 编辑器引用
  const graphiqlRef = useRef(null);
  const variablesEditorRef = useRef(null);
  const jsonEditorRef = useRef(null); // 新增的JSON编辑器引用

  // 状态管理
  const [isLoading, setIsLoading] = useState(true);
  const [endpoint, setEndpoint] = useState("/graphql");
  const [messageApi, contextHolder] = message.useMessage();
  const [query, setQuery] = useState("");
  const [variables, setVariables] = useState("");
  const [results, setResults] = useState("");
  const [jsonContent, setJsonContent] = useState(""); // 新增的JSON内容状态

  // 初始化加载效果
  useEffect(() => {
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 800);
    return () => clearTimeout(timer);
  }, []);

  // 默认查询、变量和JSON内容
  useEffect(() => {
    const defaultQuery = `# GraphQL查询示例
query GetBook($id: ID!) {
bookById(id: $id) {
  id
  name
  pageCount
  author {
    id
    firstName
    lastName
  }
}
}`;

    const defaultVariables = `{
  "id": "book-1"
}`;

    const defaultJson = `{
  "example": {
    "name": "示例数据",
    "value": 123,
    "items": [
      "item1",
      "item2",
      "item3"
    ]
  }
}`;

    setQuery(defaultQuery);
    setVariables(defaultVariables);
    setJsonContent(defaultJson); // 设置默认JSON内容
  }, []);

  // 执行查询
  const executeQuery = useCallback(() => {
    if (!query.trim()) {
      messageApi.warning("请输入查询内容");
      return;
    }

    try {
      // 解析变量（如果有）
      const variablesObj = variables.trim() ? JSON.parse(variables) : {};

      // 执行GraphQL查询
      if (graphiqlRef.current) {
        graphiqlRef.current
          .executeQuery(query, variablesObj)
          .then((result) => {
            setResults(JSON.stringify(result, null, 2));
            messageApi.success("查询已执行");
          })
          .catch((error) => {
            setResults(JSON.stringify({ errors: [error.message] }, null, 2));
            messageApi.error("查询执行失败");
          });
      }
    } catch (error) {
      messageApi.error(`变量格式错误: ${error.message}`);
    }
  }, [query, variables, messageApi]);

  // 切换文档
  const toggleExplorer = useCallback(() => {
    if (graphiqlRef.current) {
      graphiqlRef.current.toggleExplorer();
    }
  }, []);

  // 刷新编辑器
  const refreshGraphiQL = () => {
    setIsLoading(true);
    setTimeout(() => {
      setIsLoading(false);
      messageApi.info("已刷新编辑器");
    }, 500);
  };

  // 保存查询
  const saveQuery = () => {
    if (!query.trim()) {
      messageApi.warning("没有可保存的查询内容");
      return;
    }

    // 创建一个Blob并下载
    const blob = new Blob([query], { type: "application/graphql" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "query.graphql";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    messageApi.success("查询已保存");
  };

  // 格式化JSON
  const formatJson = useCallback((editorRef, content) => {
    try {
      const parsed = JSON.parse(content);
      const formatted = JSON.stringify(parsed, null, 2);
      editorRef.current.editor.setValue(formatted);
      return formatted;
    } catch (error) {
      messageApi.error(`格式错误: ${error.message}`);
      return content;
    }
  });

  // 格式化变量
  const formatVariables = useCallback(() => {
    const formatted = formatJson(variablesEditorRef, variables);
    setVariables(formatted);
  }, [formatJson, variables]);

  // 格式化结果
  const formatResults = useCallback(() => {
    if (!results) return;
    const formatted = formatJson(resultsEditorRef, results);
    setResults(formatted);
  }, [formatJson, results]);

  // 格式化JSON内容
  const formatJsonContent = useCallback(() => {
    const formatted = formatJson(jsonEditorRef, jsonContent);
    setJsonContent(formatted);
  }, [formatJson, jsonContent]);

  // 切换端点
  const handleEndpointChange = (e) => {
    setEndpoint(e.target.value);
  };

  // 创建GraphQL请求器
  const fetcher = createGraphiQLFetcher({
    url: endpoint,
    headers: {
      "Content-Type": "application/json",
    },
    method: "POST",
    body: JSON.stringify({
      query: query, // 你的GraphQL查询
    }),
  });

  // 应用端点变更
  const applyEndpoint = () => {
    setIsLoading(true);
    setTimeout(() => {
      setIsLoading(false);
      messageApi.success(`已切换到端点: ${endpoint}`);
    }, 500);
  };

  // 键盘快捷键处理
  useEffect(() => {
    const handleKeyDown = (e) => {
      // Ctrl+Enter 执行查询
      if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
        e.preventDefault();
        executeQuery();
      }
      // Ctrl+Space 打开文档
      if ((e.ctrlKey || e.metaKey) && e.key === " ") {
        e.preventDefault();
        toggleExplorer();
      }
      // Ctrl+Shift+F 格式化
      if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === "F") {
        e.preventDefault();
        if (
          document.activeElement ===
          variablesEditorRef.current.editor.getDomNode()
        ) {
          formatVariables();
        } else if (
          resultsEditorRef.current &&
          document.activeElement ===
            resultsEditorRef.current.editor.getDomNode()
        ) {
          formatResults();
        } else if (
          jsonEditorRef.current &&
          document.activeElement === jsonEditorRef.current.editor.getDomNode()
        ) {
          formatJsonContent();
        }
      }
    };

    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [
    executeQuery,
    toggleExplorer,
    formatVariables,
    formatResults,
    formatJsonContent,
  ]);

  // 探索器插件
  const plugins = [explorerPlugin()];

  // Monaco编辑器配置
  const editorOptions = {
    minimap: { enabled: false },
    scrollBeyondLastLine: false,
    fontSize: 14,
    lineNumbers: "on",
    scrollbar: {
      vertical: "auto",
      horizontal: "auto",
    },
    wordWrap: "on",
    selectOnLineNumbers: true,
  };

  // 帮助菜单
  const helpMenu = (
    <Menu>
      <Menu.Item key="docs" icon={<BookOutlined />}>
        <Link target="_blank" to="/docs">
          API文档
        </Link>
      </Menu.Item>
      <Menu.Item key="guide" icon={<FileTextOutlined />}>
        <Link target="_blank" to="/guide">
          使用指南
        </Link>
      </Menu.Item>
      <Menu.Item key="issues" icon={<QuestionCircleOutlined />}>
        <Link target="_blank" to="/issues">
          问题反馈
        </Link>
      </Menu.Item>
      <Menu.Item key="github" icon={<GithubOutlined />}>
        <Link target="_blank" href="https://github.com">
          GitHub
        </Link>
      </Menu.Item>
    </Menu>
  );

  // 结果编辑器引用
  const resultsEditorRef = useRef(null);

  return (
    <Layout style={{ minHeight: "100vh" }}>
      {contextHolder}
      <Header
        style={{
          background: "#fff",
          padding: "0 24px",
          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.06)",
        }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            height: "100%",
          }}
        >
          <div style={{ display: "flex", alignItems: "center" }}>
            <Typography.Title level={4} style={{ margin: 0, marginRight: 24 }}>
              <span style={{ color: "#1890ff" }}>GraphQL</span> 探索工具
            </Typography.Title>

            <div style={{ display: "flex", alignItems: "center" }}>
              <Input
                placeholder="GraphQL 端点"
                value={endpoint}
                onChange={handleEndpointChange}
                onPressEnter={applyEndpoint}
                style={{ width: 300, marginRight: 8 }}
              />
              <Button
                icon={<SyncOutlined />}
                size="small"
                onClick={applyEndpoint}
              />
            </div>
          </div>

          <Space size="middle">
            <Tooltip title="帮助与文档">
              <Dropdown menu={helpMenu} placement="bottomRight">
                <Button icon={<QuestionCircleOutlined />} type="text" />
              </Dropdown>
            </Tooltip>

            <Tooltip title="保存查询">
              <Button
                icon={<DownloadOutlined />}
                onClick={saveQuery}
                size="middle"
              />
            </Tooltip>

            <Tooltip title="刷新编辑器">
              <Button
                icon={<SyncOutlined />}
                onClick={refreshGraphiQL}
                size="middle"
                type="default"
              />
            </Tooltip>

            <Tooltip title="显示文档">
              <Button
                icon={<BookOutlined />}
                onClick={toggleExplorer}
                size="middle"
                type="default"
              />
            </Tooltip>

            <Tooltip title="执行查询 (Ctrl+Enter)">
              <Button
                icon={<PlayCircleOutlined />}
                onClick={executeQuery}
                size="middle"
                type="primary"
              />
            </Tooltip>
          </Space>
        </div>
      </Header>

      <Content style={{ padding: "24px", flex: 1, background: "#f0f2f5" }}>
        <Card variant="outlined" style={{ height: "calc(100vh - 130px)" }}>
          {isLoading ? (
            <div
              style={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                height: "100%",
              }}
            >
              <Spin size="large">
                <div>加载中...</div>
              </Spin>
            </div>
          ) : (
            <Tabs
              style={{ height: "100%" }}
              items={[
                {
                  key: "query",
                  label: "查询编辑器",
                  children: (
                    <div
                      style={{
                        height: "100%",
                        display: "flex",
                        flexDirection: "column",
                      }}
                    >
                      <div
                        style={{
                          flex: 1,
                          display: "flex",
                          flexDirection: "column",
                        }}
                      >
                        <div
                          style={{
                            padding: "8px",
                            borderBottom: "1px solid #e8e8e8",
                            display: "flex",
                            justifyContent: "space-between",
                          }}
                        >
                          <Text>变量</Text>
                          <Button
                            icon={<EditOutlined />}
                            size="small"
                            onClick={formatVariables}
                          >
                            格式化
                          </Button>
                        </div>
                      </div>
                      <div
                        style={{ flex: 1, borderBottom: "1px solid #e8e8e8" }}
                      >
                        <EditorJson />
                      </div>
                    </div>
                  ),
                },
                {
                  key: "results",
                  label: "结果",
                  children: (
                    <div
                      style={{
                        height: "100%",
                        display: "flex",
                        flexDirection: "column",
                      }}
                    >
                      <div
                        style={{
                          padding: "8px",
                          borderBottom: "1px solid #e8e8e8",
                          display: "flex",
                          justifyContent: "space-between",
                        }}
                      >
                        <Text>查询结果</Text>
                        <Button
                          icon={<EditOutlined />}
                          size="small"
                          onClick={formatResults}
                          disabled={!results}
                        >
                          格式化
                        </Button>
                      </div>
                      <MonacoEditor
                        ref={resultsEditorRef}
                        width="100%"
                        height="400"
                        language="json"
                        theme="vs"
                        value={results}
                        options={{ ...editorOptions, readOnly: true }}
                      />
                    </div>
                  ),
                },
                {
                  key: "graphiql",
                  label: "GraphiQL",
                  children: (
                    <GraphiQL
                      ref={graphiqlRef}
                      fetcher={fetcher}
                      plugins={plugins}
                      defaultQuery={query}
                      style={{ height: "100%", width: "100%" }}
                    />
                  ),
                },
                {
                  key: "graphiqlToolBar",
                  label: "GraphiQLToolBar",
                  children: <p>待定</p>,
                },
              ]}
            />
          )}
        </Card>
      </Content>

      <Footer
        style={{
          textAlign: "center",
          background: "#fff",
          borderTop: "1px solid #e8e8e8",
        }}
      >
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
          }}
        >
          <Text type="secondary">© 2025 GraphQL 探索工具 | 版本 1.0.0</Text>
          <Space size="middle" style={{ marginTop: 8 }}>
            <Link href="/docs" target="_blank" icon={<FileTextOutlined />}>
              API文档
            </Link>
            <Link href="/guide" target="_blank">
              使用指南
            </Link>
            <Link href="/issues" target="_blank">
              问题反馈
            </Link>
            <Link
              href="https://github.com"
              target="_blank"
              icon={<GithubOutlined />}
            >
              GitHub
            </Link>
          </Space>
        </div>
      </Footer>
    </Layout>
  );
};

export default GraphQLExplorer;
